package com.gehj.uhttp;


//import com.ygsj.VehicleInfoEntity;


import android.content.Context;
import android.content.res.AssetManager;
import android.text.TextUtils;


import com.gehj.alluitls.DateUtil_gehj;
import com.gehj.alluitls.androidUtils.LogUtil;
import com.gehj.uhttp.entity.CarTraceInfoXmlEntity;
import com.gehj.uhttp.entity.Client;
import com.gehj.uhttp.entity.Clients;
import com.gehj.uhttp.entity.MonthSummary;
import com.gehj.uhttp.entity.Product;
import com.gehj.uhttp.entity.RecordItem;
import com.gehj.uhttp.entity.RecordListBean;
import com.gehj.uhttp.entity.RecordListEntity;
import com.gehj.uhttp.entity.RecordListEntity_;
import com.gehj.uhttp.entity.UserEntity;
import com.gehj.uhttp.entity.VehicleInfoEntity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import fr.arnaudguyon.xmltojsonlib.XmlToJson;

//import fr.arnaudguyon.xmltojsonlib.XmlToJson;

/**
 * Created by Administrator on 2016/10/24.
 * 原生解析解析复杂的json可以进行参考;
 */

public class ParJson {


    /**
     * 返回map的处理
     * */
    public static Map<String,Object> isUpdateNormal(String json) {
        JSONObject jsonObject = null;
        Map<String,Object> map = new HashMap<>();
        try {
            jsonObject = new JSONObject(json);
            int code = jsonObject.optInt("code");
            String msg = jsonObject.optString("msg");
            map.put("code",code);
            map.put("msg",msg);

        } catch (JSONException e) {
            e.printStackTrace();
        }
       return  map;
    }


    /**
     * 分页 最初始的
     * @return
     */
    public static RecordListEntity getRecordList(String json) {
        RecordListEntity recordListEntity =null;
        List<RecordListBean> recordListBeans = null;
        RecordListBean bean = null;

        try {
            recordListEntity = new RecordListEntity();
            recordListBeans = new ArrayList<>();
            JSONObject jo1 = new JSONObject(json);//最外层的jsonObject
            int pages = jo1.optInt("pages");
            recordListEntity.setPages(pages);

            //第二层实体

            JSONObject jo2 = (JSONObject) jo1.getJSONArray("records").get(0);

            Double exchangeAmount = jo2.optDouble("exchangeAmount");
            int incomeAmount = jo2.optInt("incomeAmount");
            String yearMonth = jo2.optString("yearMonth");

            recordListEntity.setExchangeAmount(exchangeAmount);
            recordListEntity.setIncomeAmount(incomeAmount);
            recordListEntity.setYearMonth(yearMonth);

            JSONArray jsonArray = jo2.optJSONArray("exchangeRecordInfoList");
            for (int i = 0; i < jsonArray.length(); i++) {
                bean = new RecordListBean();
                JSONObject jo3 = (JSONObject) jsonArray.get(i);
                bean.setAmountType(jo3.optInt("amountType"));
                bean.setBrokerId(jo3.optString("brokerId"));
                bean.setBusinessId(jo3.optString("businessId"));
                bean.setBusinessName(jo3.optString("businessName"));
                bean.setCreateTime(jo3.optString("createTime"));
                bean.setDriverId(jo3.optString("driverId"));
                bean.setExchangeAmount(jo3.optDouble("exchangeAmount"));
                bean.setExchangeId(jo3.optString("exchangeId"));
                bean.setExchangeNumber(jo3.optString("exchangeNumber"));
                bean.setExchangeTypeName(jo3.optString("exchangeTypeName")) ;
                bean.setId(jo3.optString("id"));
                bean.setOptUserId(jo3.optString("optUserId"));
                bean.setOrderId(jo3.optString("orderId"));
                bean.setOrderNumber(jo3.optString("orderNumber"));
                bean.setOrgName(jo3.optString("orgName"));
                bean.setProductType(jo3.optInt("productType"));
                bean.setRealname(jo3.optString("realname"));
                bean.setUsername(jo3.optString("username"));
                //bean.setNum(jo3.optString("num"));

                recordListBeans.add(bean);
            }

            recordListEntity.setRecordLists(recordListBeans);




        } catch (JSONException e) {
            e.printStackTrace();
        }

        return recordListEntity;
    }


    /**
     * 分月+分页 + 自定义头（粘性头部）
     * @param json
     * @return
     */
    public static RecordListEntity_ getRecordList_(String json) {
        RecordListEntity_ recordListEntity_ =null;
        RecordItem recordItem = null;
        MonthSummary summary = null;
        List<RecordItem> recordItems = null;
        RecordListBean bean = null;


        try {
            recordListEntity_ = new RecordListEntity_();
            recordItems = new ArrayList<>();
            JSONObject jo1 = new JSONObject(json);//最外层的jsonObject
            int pages = jo1.optInt("pages");
            recordListEntity_.setPages(pages);

            //第二层实体
            JSONArray ja_2 =  jo1.optJSONArray("records");
            for (int i = 0; i <ja_2.length() ; i++) {
                   summary = new MonthSummary();

                   JSONObject ja_2_obj =  ja_2.getJSONObject(i);
                   Double exchangeAmount =  ja_2_obj.optDouble("exchangeAmount");
                   String yearMonth =  ja_2_obj.optString("yearMonth");
                   int month = 0;
                if (!TextUtils.isEmpty(yearMonth)){
                     month =   DateUtil_gehj.str2Month(yearMonth,DateUtil_gehj.yearAndMonthFormat);
                   }else {
                    month = 0;
                 }

                   LogUtil.e("addhead",month+"");
                   summary.setGroupId(month);
                   summary.setYearMonth(yearMonth);
                   summary.setExchangeAmount(exchangeAmount);



                   recordItem = new RecordItem(RecordItem.SECTION,summary);//对汇总头进行添加；


                   recordItem.setGroupID(month);


                   recordItems.add(recordItem); //添加头

                   //recordListEntity_.setExchangeAmount(exchangeAmount);
                   //recordListEntity_.setYearMonth(yearMonth);


                  JSONArray ja_3 = ja_2_obj.optJSONArray("exchangeRecordInfoList");
                    for (int j = 0; j < ja_3.length(); j++) { //第三层的jsonAarrry
                        JSONObject ja_3_obj = ja_3.getJSONObject(j); //第三层的兑换记录实体；
                        bean = new RecordListBean();
                        bean.setGroupId(month); //自己把头塞进去
                        bean.setAmountType(ja_3_obj.optInt("amountType"));
                        bean.setBrokerId(ja_3_obj.optString("brokerId"));
                        bean.setBusinessId(ja_3_obj.optString("businessId"));
                        bean.setBusinessName(ja_3_obj.optString("businessName"));
                        bean.setCreateTime(ja_3_obj.optString("createTime"));
                        bean.setDriverId(ja_3_obj.optString("driverId"));
                        bean.setExchangeAmount(ja_3_obj.optDouble("exchangeAmount"));
                        bean.setExchangeId(ja_3_obj.optString("exchangeId"));
                        bean.setExchangeNumber(ja_3_obj.optString("exchangeNumber"));
                        bean.setExchangeTypeName(ja_3_obj.optString("exchangeTypeName")) ;
                        bean.setId(ja_3_obj.optString("id"));
                        bean.setOptUserId(ja_3_obj.optString("optUserId"));
                        bean.setOrderId(ja_3_obj.optString("orderId"));
                        bean.setOrderNumber(ja_3_obj.optString("orderNumber"));
                        bean.setOrgName(ja_3_obj.optString("orgName"));
                        bean.setProductType(ja_3_obj.optInt("productType"));
                        bean.setRealname(ja_3_obj.optString("realname"));
                        bean.setUsername(ja_3_obj.optString("username"));
                        recordItem = new RecordItem(RecordItem.ITEM,bean);


                        recordItem.setGroupID(month);


                        recordItems.add(recordItem);
                    }
             }

                recordListEntity_.setRecordItemListList(recordItems);

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return recordListEntity_;
    }


    /**
     * 分月+分页 + 自定义头 为了适应--> StickyListHeaders ，另外一种思路
     * @param json
     * @return
     */
    public static RecordListEntity  getRecordList_head(String json) {
        RecordListEntity recordListEntity =null;
       // RecordItem recordItem = null;
       // MonthSummary summary = null;
       // List<RecordItem> recordItems = null;
        List<RecordListBean> recordListBeans = null;
        RecordListBean bean = null;


        try {
            recordListEntity = new RecordListEntity();
            //recordItems = new ArrayList<>();
            recordListBeans = new ArrayList<>();
            JSONObject jo1 = new JSONObject(json);//最外层的jsonObject
            int pages = jo1.optInt("pages");
            recordListEntity.setPages(pages);

            //第二层实体
            // JSONObject jo2 = (JSONObject) jo1.getJSONArray("records").get(0);
            JSONArray ja_2 =  jo1.optJSONArray("records");
            for (int i = 0; i <ja_2.length() ; i++) {
                //summary = new MonthSummary();

                JSONObject ja_2_obj =  ja_2.getJSONObject(i);
                Double exchangeTotalAmount =  ja_2_obj.optDouble("exchangeAmount");
                String yearMonth =  ja_2_obj.optString("yearMonth");
                int month = 0;
                if (!TextUtils.isEmpty(yearMonth)){
                    month =   DateUtil_gehj.str2Month(yearMonth,DateUtil_gehj.yearAndMonthFormat);
                }else {
                    month = 0;
                }


                //LogUtil.e("addhead",month+"");
                //summary.setGroupId(month);
                //summary.setYearMonth(yearMonth);
                //summary.setExchangeAmount(exchangeAmount);


                //recordItem = new RecordItem(RecordItem.SECTION,summary);//对汇总头进行添加；
                //recordItem.setGroupID(month);
                //recordItems.add(recordItem); //添加头

                //recordListEntity_.setExchangeAmount(exchangeAmount);
                //recordListEntity_.setYearMonth(yearMonth);

                JSONArray ja_3 = ja_2_obj.optJSONArray("exchangeRecordInfoList");
                for (int j = 0; j < ja_3.length(); j++) { //第三层的jsonAarrry
                    JSONObject ja_3_obj = ja_3.getJSONObject(j); //第三层的兑换记录实体；
                    bean = new RecordListBean();
                    //bean.setGroupId(month);
                    bean.setAmountType(ja_3_obj.optInt("amountType"));
                    bean.setBrokerId(ja_3_obj.optString("brokerId"));
                    bean.setBusinessId(ja_3_obj.optString("businessId"));
                    bean.setBusinessName(ja_3_obj.optString("businessName"));
                    bean.setCreateTime(ja_3_obj.optString("createTime"));
                    bean.setDriverId(ja_3_obj.optString("driverId"));
                    bean.setExchangeAmount(ja_3_obj.optDouble("exchangeAmount"));
                    bean.setExchangeId(ja_3_obj.optString("exchangeId"));
                    bean.setExchangeNumber(ja_3_obj.optString("exchangeNumber"));
                    bean.setExchangeTypeName(ja_3_obj.optString("exchangeTypeName")) ;
                    bean.setId(ja_3_obj.optString("id"));
                    bean.setOptUserId(ja_3_obj.optString("optUserId"));
                    bean.setOrderId(ja_3_obj.optString("orderId"));
                    bean.setOrderNumber(ja_3_obj.optString("orderNumber"));
                    bean.setOrgName(ja_3_obj.optString("orgName"));
                    bean.setProductType(ja_3_obj.optInt("productType"));
                    bean.setRealname(ja_3_obj.optString("realname"));
                    bean.setUsername(ja_3_obj.optString("username"));
                    //recordItem = new RecordItem(RecordItem.ITEM,bean);

                    bean.setGroupId(month);
                   //recordItem.setGroupID(month);
                    bean.setExchangeTotalAmount(exchangeTotalAmount);
                    bean.setYearMonth(yearMonth);
                    recordListBeans.add(bean);
                    //recordItems.add(recordItem);

                }
            }
            recordListEntity.setRecordLists(recordListBeans);
            //recordListEntity_.setRecordItemListList(recordItems);

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return recordListEntity;
    }


    /**
     * 比较典型数据
     * @param json
     * @return
     */
    public  static  List<Product> getGoodsList(String json) {
        List<Product> list_product = null;

        try {
            JSONObject jsonObject = new JSONObject(json);
            JSONArray records = jsonObject.optJSONArray("records");
            list_product = new ArrayList<>();
            for (int i = 0; i < records.length(); i++) {
               JSONObject jo_product = (JSONObject) records.get(i);
               Product product = new Product();
                String id = jo_product.optString("id");//商品id
                String typeName = jo_product.optString("typeName");//种类
                String description = jo_product.optString("description");//描述
                String createTime = jo_product.optString("createTime");//创建时间
                String productImg = jo_product.optString("productImg");//图片地址
                Double exchangeAmount = jo_product.optDouble("exchangeAmount");//价格

                String productUnit = jo_product.optString("productUnit");//单位
                int shelf = jo_product.optInt("shelf");//上下架状态(1：正常，2:已下架)
                String businessId = jo_product.optString("businessId");
                String typeId = jo_product.optString("exchangeTypeId");


                product.setId(id);
                product.setTypeName(typeName);
                product.setDescription(description);
                product.setCreateTime(createTime);
                product.setProductImg(productImg);
                product.setExchangeAmount(exchangeAmount);
                product.setProductUnit(productUnit);
                product.setShelf(shelf);
                product.setBusinessId(businessId);
                product.setExchangeTypeId(typeId);


               list_product.add(product);
            }



        } catch (JSONException e) {
            e.printStackTrace();
        }
        return  list_product;

    }

    /**
     * 登录后返回信息
     * @param json
     * @return
     */
    public static UserEntity getUserInfo_login(String json) {
        UserEntity userEntity = null;
        try {
            userEntity = new UserEntity();
            JSONObject jsonObject = new JSONObject(json);
                String access_token = jsonObject.optString("access_token");
                String token_type = jsonObject.optString("token_type");
                int expires_in = jsonObject.optInt("expires_in");
                String scope = jsonObject.optString("scope");
                int tenant_id = jsonObject.optInt("tenant_id");
                String common_mobile = jsonObject.optString("common_mobile");
                int dept_id = jsonObject.optInt("dept_id");
                String user_id = jsonObject.optString("user_id");
                String username = jsonObject.optString("username");

                userEntity.setAccess_token(access_token);
                userEntity.setToken_type(token_type);
                userEntity.setExpires_in(expires_in);
                userEntity.setScope(scope);
                userEntity.setTenant_id(tenant_id);
                userEntity.setCommon_mobile(common_mobile);
                userEntity.setDept_id(dept_id);
                userEntity.setUser_id(user_id);
                userEntity.setUsername(username);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return userEntity;
    }





    /**
     * 比较典型：客户管理的分页数据，项目中没有用到
     * @param json
     * @return
     */
    public static Clients getClientList(String json) {
        Clients clients = new Clients();

        List<Client> clientList;
        try {
            JSONObject jsonObject = new JSONObject(json);
            int total = jsonObject.optInt("total");
            int size = jsonObject.optInt("size");
            int current = jsonObject.optInt("current");
            int pages = jsonObject.optInt("pages");
            clients.setTotal(total); clients.setSize(size);clients.setCurrent(current);clients.setPages(pages);

            JSONArray records = jsonObject.optJSONArray("records");
            clientList = new ArrayList<>();
            for (int i = 0; i < records.length();i++) {
                Client client = new Client();
                JSONObject jo_record = records.getJSONObject(i);
                String address = jo_record.optString("address");
                int bindStatus = jo_record.optInt("bindStatus");
                String businessName = jo_record.optString("businessName");
                String mobilePhone = jo_record.optString("mobilePhone");
                String username = jo_record.optString("username");
                client.setAddress(address);
                client.setStatus(bindStatus);
                client.setClientName(businessName);
                client.setPhone(mobilePhone);
                client.setName(username);
                clientList.add(client);
            }
            clients.setRecords(clientList);


        } catch (JSONException e) {
            e.printStackTrace();
        }

        return clients;
    }


    /**
     * 具体参考 https://github.com/smart-fun/XmlToJson
     * @param fileName
     * @param context
     * @return
     */
    //xml转json
    public static String getJsonFromXml(String fileName, Context context) {
        InputStream inputStream = null;
        XmlToJson xmlToJson = null;
        String json = null;
        try {
            AssetManager assetManager = context.getAssets();
            inputStream = assetManager.open(fileName);
            if (inputStream != null) {
                xmlToJson = new XmlToJson.Builder(inputStream, "UTF-8").build();
                json = xmlToJson.toJson().toString();
                inputStream.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return json;
    }


    /**
     * xml --> json 具体的json解析
     */
    public static List<CarTraceInfoXmlEntity> getXmlEntity(String json) {
        List<CarTraceInfoXmlEntity> infoXmlEntities = null;

        try {
            JSONObject object = new JSONObject(json);
            JSONObject o_data = object.getJSONObject("data");
            JSONArray a_history = o_data.getJSONArray("HistoryTrack");
            infoXmlEntities = new ArrayList<>();
            int size = a_history.length();
            for (int i = 0; i < size; i++) {
                JSONObject o = a_history.getJSONObject(i);
                String last_lon = o.getString("last_lon");
                String last_lat = o.getString("last_lat");
                String location = o.getString("location");
                String lastUpdateTime = o.getString("lastUpdateTime");
                CarTraceInfoXmlEntity carTraceInfoXmlEntity = new CarTraceInfoXmlEntity();
                carTraceInfoXmlEntity.setLast_lon(last_lon);
                carTraceInfoXmlEntity.setLast_lat(last_lat);
                carTraceInfoXmlEntity.setLocation(location);
                carTraceInfoXmlEntity.setLastUpdateTime(lastUpdateTime);
                infoXmlEntities.add(carTraceInfoXmlEntity);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return infoXmlEntities;
    }


    /**
     * 把固定数据变成listview进行处理
     * 奇葩的处理方法
     */

 public static List<VehicleInfoEntity> getCardInfo(String json) {
        List<VehicleInfoEntity> list = null;
        try {
            JSONObject jsonObject = new JSONObject(json);
            // String flag = jsonObject.getString("flag");
            //  if (null!=flag && (flag.equals("6")||flag.equals("7"))) {
            //   JSONArray jsonArray = (JSONArray) jsonObject.opt("list");
            //     JSONObject obj1 = (JSONObject) jsonArray.get(0);
            list = new ArrayList<>();
            int flag = jsonObject.getInt("flag");
            JSONObject jsonObject_dataInfo = jsonObject.getJSONObject("data");
            if (flag == 0) {
            String billSerial = jsonObject_dataInfo.optString("billSerial", "nothingIt");
            if (!billSerial.equals("nothingIt")) {
                list.add(new VehicleInfoEntity("票号", billSerial));
            }

            String contractDate = jsonObject_dataInfo.optString("contractDate", "nothingIt");
            if (!contractDate.equals("nothingIt")) {
                list.add(new VehicleInfoEntity("合同日期", contractDate));
            }


            String contractNumber = jsonObject_dataInfo.optString("contractNumber", "nothingIt");
            if (!contractNumber.equals("nothingIt")) {
                list.add(new VehicleInfoEntity("合同号", contractNumber));
            }

            String shipper = jsonObject_dataInfo.optString("shipper", "nothingIt");
            if (!shipper.equals("nothingIt")) {
                list.add(new VehicleInfoEntity("发货方", shipper));
            }

            String ShippingAddress = jsonObject_dataInfo.optString("ShippingAddress", "nothingIt");
            if (!ShippingAddress.equals("nothingIt")) {
                list.add(new VehicleInfoEntity("发货单位地址", ShippingAddress));
            }

            String receiver = jsonObject_dataInfo.optString("receiver", "nothingIt");
            if (!receiver.equals("nothingIt")) {
                list.add(new VehicleInfoEntity("收货方", receiver));
            }

            String receiverAddress = jsonObject_dataInfo.optString("receiverAddress", "nothingIt");
            if (!receiverAddress.equals("nothingIt")) {
                list.add(new VehicleInfoEntity("收货单位地址", receiverAddress));
            }


            String coalType = jsonObject_dataInfo.optString("coalType", "nothingIt");
            if (!coalType.equals("nothingIt")) {
                list.add(new VehicleInfoEntity("煤种", coalType));
            }


            String unitPrice = jsonObject_dataInfo.optString("unitPrice", "nothingIt");
            if (!unitPrice.equals("nothingIt")) {
                list.add(new VehicleInfoEntity("单价", unitPrice));
            }

            String suttle = jsonObject_dataInfo.optString("suttle", "nothingIt");
            if (!suttle.equals("nothingIt")) {
                list.add(new VehicleInfoEntity("净重", suttle));
            }

            String amount = jsonObject_dataInfo.optString("amount", "nothingIt");
            if (!amount.equals("nothingIt")) {
                list.add(new VehicleInfoEntity("金额", amount));
            }

            String CarLicense = jsonObject_dataInfo.optString("CarLicense", "nothingIt");
            if (!CarLicense.equals("nothingIt")) {
                list.add(new VehicleInfoEntity("车号", CarLicense));
            }


            String maxLoad = jsonObject_dataInfo.optString("maxLoad", "nothingIt");
            if (!maxLoad.equals("nothingIt")) {
                list.add(new VehicleInfoEntity("核定载重", maxLoad));
            }

            String vehicleModel = jsonObject_dataInfo.optString("vehicleModel","nothingIt");
            if (!vehicleModel.equals("nothingIt")) {
                list.add(new VehicleInfoEntity("车型", vehicleModel));
            }


            String roughWeight = jsonObject_dataInfo.optString("roughWeight","nothingIt");
            if (!roughWeight.equals("nothingIt")) {
                list.add(new VehicleInfoEntity("过磅毛重", roughWeight));
            }

            String kerbWeight = jsonObject_dataInfo.optString("kerbWeight","nothingIt");
            if (!kerbWeight.equals("nothingIt")) {
                list.add(new VehicleInfoEntity("过磅皮重", kerbWeight));
            }

            String netWeight = jsonObject_dataInfo.optString("netWeight","nothingIt");
            if (!netWeight.equals("nothingIt")) {
                list.add(new VehicleInfoEntity("过磅净重", netWeight));
            }


            String DriverName = jsonObject_dataInfo.optString("DriverName","nothingIt");
            if (!DriverName.equals("nothingIt")) {
                list.add(new VehicleInfoEntity("驾驶员姓名", DriverName));
            }


            String DriverPhoneNum = jsonObject_dataInfo.optString("DriverPhoneNum","nothingIt");
            if (!DriverPhoneNum.equals("nothingIt")) {
                list.add(new VehicleInfoEntity("驾驶员电话", DriverPhoneNum));
            }

            String clCydwname = jsonObject_dataInfo.optString("ClCydwname","nothingIt");
            if (!clCydwname.equals("nothingIt")) {
                list.add(new VehicleInfoEntity("承运单位", clCydwname));
            }
        }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return list;
    }


//TODO av_4_5 解析两层的实体 listview 侧边栏带abcd的







}
